<template>
  <el-drawer :title="form.id ? (detail ? '详情' : '编辑') : '添加'" v-model="visible" size="50%">
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="100px" :disabled="detail"
             v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('basDicSet.dictName')" prop="text">
            <el-input v-model="form.text" :placeholder="$t('basDicSet.EnterDictionaryItemName')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('basDicSet.dictValue')" prop="code">
            <el-input v-model="form.code" :placeholder="$t('basDicSet.EnterDictionaryItemValue')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('basDicSet.sort')" prop="sort">
            <el-input v-model="form.sort" :placeholder="$t('basDicSet.enterSort')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('basDicSet.remark')" prop="remark">
            <el-input v-model="form.remark" :placeholder="$t('basDicSet.remark')"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <sc-form-table
            v-model="form.basDicItemList"
            :addTemplate="childTemp"
            @delete="deleteChild"
            :placeholder="$t('table.noDataAvailable')"
        >
          <el-table-column align="center" :label="$t('basDicSet.dictName')" prop="text">
            <template #default="{ row, $index }">
              <el-form-item label-width="0px" :prop="`basDicItemList.${$index}.text`"
                            :rules="[{ required: true, trigger: 'blur' }]">
                <el-input v-model="row.text" style="width: 100%"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('basDicSet.dictValue')" prop="value">
            <template #default="{ row, $index }">
              <el-form-item label-width="auto" :prop="`basDicItemList.${$index}.value`"
                            :rules="[{ required: true, trigger: 'blur'},{required: true , trigger: 'change'}]">
                <el-input v-model="row.value" style="width: 100%"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('basDicSet.defaultSelected')" prop="selected">
            <template #default="{ row, $index }">
              <el-form-item label-width="auto" :prop="`basDicItemList.${$index}.selected`"
                            :rules="[{ required: false, trigger: 'blur' }]">
                <!--<el-input v-model="row.selected" style="width: 100%" />-->
                <el-switch style="margin: auto"
                           v-model="row.selected"
                           inline-prompt
                           size="large"
                           active-text="true"
                           inactive-text="false"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('basDicSet.sort')" prop="sort">
            <template #default="{ row, $index }">
              <el-form-item label-width="auto" :prop="`basDicItemList.${$index}.sort`"
                            :rules="[{ required: false, trigger: 'blur' }]">
                <!--改数字输入框-->
                <el-input-number v-model="row.sort" :min="0" :max="100" :label="$t('basDicSet.sort')"/>

              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('basDicSet.remark')" prop="remark">
            <template #default="{ row, $index }">
              <el-form-item label-width="auto" :prop="`basDicItemList.${$index}.remark`"
                            :rules="[{ required: false, trigger: 'blur' }]">
                <el-input label-width="auto" v-model="row.remark" style="width: 100%"/>
              </el-form-item>
            </template>
          </el-table-column>
          <!--<el-table-column label="语言" prop="language">-->
          <!--  <template #default="{ row, $index }">-->
          <!--    <el-form-item label-width="auto" idth :prop="`basDicItemList.${$index}.language`"-->
          <!--                  :rules="[{ required: false, trigger: 'blur' }]">-->
          <!--      <el-input v-model="row.language" style="width: 100%"/>-->
          <!--    </el-form-item>-->
          <!--  </template>-->
          <!--</el-table-column>-->
          <!--<el-table-column label="颜色" prop="valueColour">-->
          <!--  <template #default="{ row, $index }">-->
          <!--    <el-form-item label-width="auto" :prop="`basDicItemList.${$index}.valueColour`"-->
          <!--                  :rules="[{ required: false, trigger: 'blur' }]">-->
          <!--      <el-input v-model="row.valueColour" style="width: 100%"/>-->
          <!--    </el-form-item>-->
          <!--  </template>-->
          <!--</el-table-column>-->
        </sc-form-table>
      </el-row>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false"  icon="close">{{$t('operation.Cancel')}}</el-button>
          <el-button type="primary" @click="onSubmit"  icon="check" :disabled="loading">{{$t('operation.confirm')}}</el-button>
        </span>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="BasDicSetDialog">
import {useMessage} from "/@/hooks/message";
import {addObj, delChildObj, getObj, putObj} from '/@/api/platform/digital/basDicSet'
import {rule} from "/@/utils/validate";

const scFormTable = defineAsyncComponent(() => import('/@/components/FormTable/index.vue'));
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const detail = ref(false);

// 定义校验规则
// 定义表单校验规则
const dataRules = reactive({
  text: [
    {required: true, message: "请输入字典项名称", trigger: 'blur'},
  ],
  code: [
    {required: true, message: "请输入字典项代码", trigger: 'blur'},
    {validator: rule.letterAndNumber, trigger: 'blur'}
  ]
})
// 验证字典项的唯一性
const validateUnique = (rule: any, value: any, callback: any) => {
  if (value) {
    let arr = form.basDicItemList.filter((item: any) => item.value === value);
    if (arr.length >= 2) {
      callback(new Error('字典项值重复'));
    } else {
      callback();
    }
  } else {
    callback();
  }
}

// 提交表单数据
const form = reactive({
  id: '',
  text: '',
  code: '',
  sort: '',
  remark: '',
  basDicItemList: [],
});

const childTemp = reactive({
  id: '',
  masterId: '',
  text: '',
  value: '',
  selected: false,
  sort: '',
  remark: '',
  language: '',
  valueColour: '',
  tenantId: '',
  delFlag: 0,
  createBy: '',
  creationTime: '',
  createUserNo: '',
  createUserName: '',
  lastModifyTime: '',
  lastModifyUserName: '',
  lastModifyUserNo: '',
  attribute1: '',
  attribute2: '',
  attribute3: '',
})


// 打开弹窗
const openDialog = (id: string, isDetail: boolean) => {
  visible.value = true
  detail.value = isDetail
  form.id = ''

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
    form.basDicItemList = [];
  });

  // 获取basDicSet信息
  if (id) {
    form.id = id
    getBasDicSetData(id)
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};
// 删除子表数据
const deleteChild = async (obj: { id: string }) => {
  if (obj.id) {
    try {
      await delChildObj([obj.id]);
      useMessage().success('删除成功');
    } catch (err: any) {
      useMessage().error(err.msg);
    }
  }
};

// 初始化表单数据
const getBasDicSetData = (id: string) => {
  // 获取数据
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
    // 将form中的basDicItemList中的selected 为空的赋值false
    form?.basDicItemList?.forEach((item: any) => {
      if (!item.selected || item.selected === "false") {
        item.selected = false
      } else {
        item.selected = true
      }
    })
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>